// 预加载配置资源
import initConfig from "./initConfig.js";
import { STORAGE_SYNC, MODE, ENABLE_PROXY } from "./constants.js";
import { switchPopupIcon, debounce } from "./utils.js";
import tabManager from "./manager/TabManager.js";
import ProxyManager from "./config/ProxyManager.js";

const proxyManager = new ProxyManager();
const { SYSTEM, FIXED_SERVERS } = chrome.proxy.Mode;
const tabs = chrome.tabs;
const { LOADING: TAB_LOADING, COMPLETE: TAB_COMPLETE } = tabs.TabStatus;
let tabLoadingList = [];

// 默认配置
let proxyRule = {};

const systemProxyConfig = {
	mode: SYSTEM,
};
const fixedServersProxyConfig = {
	mode: FIXED_SERVERS,
	rules: {
		singleProxy: proxyRule,
	},
};

const loadingTabByProxyDebounce = debounce(loadingTabByProxy, 20);

let proxyConfig;

// 初始化
init();

chrome.proxy.onProxyError.addListener((details) => {
	console.log(details);
});

tabs.onCreated.addListener(async ({ id: tabId }) => {
	const loadingFlag = await hasLoadingTab(tabId);
	if (loadingFlag) {
		return;
	}

	switchMode(SYSTEM);
});

// 切换标签页
tabs.onActivated.addListener(async ({ tabId }) => {
	// 加载完毕才能切换代理
	const { status } = await tabs.get(tabId);

	if (status === TAB_LOADING && tabLoadingList.indexOf(tabId) === -1) {
		tabLoadingList.push(tabId);
		return;
	}

	const loadingFlag = await hasLoadingTab(tabId);
	if (loadingFlag) {
		return;
	}

	switchModeByTabId(tabId);
});

tabs.onUpdated.addListener((tabId, { status }) => {
	if (!status) {
		return;
	}

	const index = tabLoadingList.indexOf(tabId);

	switch (status) {
		case TAB_LOADING:
			if (index === -1) {
				tabLoadingList.push(tabId);
				if (tabLoadingList.length === 1) {
					loadingTabByProxyDebounce();
				}
			}

			break;
		case TAB_COMPLETE:
			tabLoadingList.splice(index, 1);
			loadingTabByProxy();
			break;
	}
});

STORAGE_SYNC.onChanged.addListener(async (objects) => {
	let { enableProxy } = objects;

	if (enableProxy) {
		if (!enableProxy.newValue) {
			return;
		}

		const { protocol, ip, port } = enableProxy.newValue;
		proxyRule = {
			scheme: protocol,
			host: ip,
			port,
		};

		// 更改rules
		fixedServersProxyConfig.rules.singleProxy = proxyRule;
	}
});

async function init() {
	// 初始化配置资源
	await initConfig();

	// 模式
	let { mode, enableProxy } = await STORAGE_SYNC.get([MODE, ENABLE_PROXY]);

	if (enableProxy) {
		const { protocol, ip, port } = enableProxy;
		proxyRule = {
			scheme: protocol,
			host: ip,
			port,
		};

		fixedServersProxyConfig.rules.singleProxy = proxyRule;
	}

	switchMode(mode);
	switchPopupIcon(mode);
}

function switchMode(mode) {
	switch (mode) {
		case SYSTEM:
			proxyConfig = systemProxyConfig;
			break;
		case FIXED_SERVERS:
			proxyConfig = fixedServersProxyConfig;
			break;
	}

	switchPopupIcon(mode);
	STORAGE_SYNC.set({ mode });

	// 设置生效
	resetProxyConfig();
}

function resetProxyConfig() {
	chrome.proxy.settings.set({ value: proxyConfig, scope: "regular" });
}

async function loadingTabByProxy() {
	if (!tabLoadingList.length) {
		return;
	}

	const tabId = tabLoadingList[0];
	switchModeByTabId(tabId);
	tabs.reload(tabId);
}

async function hasLoadingTab(tabId) {
	let loadingTabs = await tabs.query({ status: TAB_LOADING });
	loadingTabs = loadingTabs.filter((tab) => tab.id !== tabId);
	return loadingTabs.length;
}

async function switchModeByTabId(tabId) {
	// 切换成 本标签页的代理
	const proxyId = await tabManager.get(tabId);

	if (!proxyId) {
		switchMode(SYSTEM);
	} else {
		proxyManager.enableProxy(proxyId);
		switchMode(FIXED_SERVERS);
	}
}
